package com.ruoyi.web.controller.app;

import com.ruoyi.business.domain.TDevice;
import com.ruoyi.business.service.ITDeviceService;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.domain.entity.SysUser;
import com.ruoyi.common.core.page.TableDataInfo;
import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.business.domain.TDeviceLog;
import com.ruoyi.business.service.ITDeviceLogService;
import com.ruoyi.framework.web.service.SysPermissionService;
import com.ruoyi.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.Collections;
import java.util.List;
import java.util.Set;

/**
 * B端 设备管理接口
 */
@RestController
@RequestMapping("/b-api/device")
public class BapiDeviceController extends BaseController {

    @Autowired
    private ITDeviceService deviceService;

    @Autowired
    private ITDeviceLogService deviceLogService;

    @Autowired
    private SysPermissionService permissionService;

    @Autowired
    private ISysUserService userService;

    /**
     * 获取设备列表 (合作商/经销商通用)
     */
    @GetMapping("/list")
    public TableDataInfo list(TDevice device) {
        // 关键：我们不再手动设置 partner_id 或 distributor_id
        // 这个工作将交给 @DataScope 注解自动完成

        startPage();
        List<TDevice> list = deviceService.selectTDeviceList(device);
        return getDataTable(list);
    }

    /**
     * 获取设备详情
     */
    @GetMapping("/{deviceId}")
    public AjaxResult getInfo(@PathVariable Long deviceId) {
        TDevice device = deviceService.selectTDeviceByDeviceId(deviceId);
        // 同样，数据权限的校验也应该在Service层完成，但Controller层做一个二次保障
        // 这里我们先简化，后续在Service层加强
        return AjaxResult.success(device);
    }

    /**
     * 获取单个设备的日志列表
     */
    @GetMapping("/log/{deviceId}")
    public TableDataInfo getDeviceLog(@PathVariable Long deviceId) {
        // 步骤1：安全校验，确保用户有权查看该设备的日志
        TDevice device = deviceService.selectTDeviceByDeviceId(deviceId);
        Long currentUserId = SecurityUtils.getUserId();
        SysUser user = userService.selectUserByUserName(SecurityUtils.getUsername());
        Set<String> roles = permissionService.getRolePermission(user);

        boolean hasPermission = false;
        if (device != null) {
            if (roles.contains("partner") && currentUserId.equals(device.getPartnerId())) {
                hasPermission = true;
            } else if (roles.contains("distributor") && currentUserId.equals(device.getDistributorId())) {
                hasPermission = true;
            }
        }

        if (!hasPermission) {
            // 如果无权访问，返回空列表和错误信息
            return getDataTable(Collections.emptyList());
        }

        // 步骤2：查询日志
        TDeviceLog queryParam = new TDeviceLog();
        queryParam.setDeviceId(deviceId);

        startPage();
        List<TDeviceLog> logList = deviceLogService.selectTDeviceLogList(queryParam);
        return getDataTable(logList);
    }
}